/**
 * Created by Administrator on 2016/12/14.
 */
//public method 业务层面方法
import Vue from 'vue'
import {imgBaseUrl} from 'config/env.js'

//错误提示
export function errorPrompt(tipStr){
  Vue.$toast({
    message: tipStr,
    //position: 'top',
    duration: 3000,
    className: "fail"
  });
};
//成功提示
export function successPrompt(tipStr){
  Vue.$toast({
    message: tipStr,
    //position: 'top',
    duration: 3000,
    className: "success"
  });
}
//加载中
export function loading() {
  Vue.$indicator.open({
    text: '加载中...',
    spinnerType: 'fading-circle'
  });
}
//关闭加载中动画
export function closeLoading() {
  Vue.$indicator.close();
}

//获得角标
export function indexOf(arr, str){
  // 如果可以的话，调用原生方法
  if(arr && arr.indexOf){
    return arr.indexOf(str);
  }
  var len = arr.length;
  for(var i = 0; i < len; i++){
    // 定位该元素位置
    if(arr[i] == str){
      return i;
    }
  }
  // 数组中不存在该元素
  return -1;
}

//标准时间转化字符串时间
Date.prototype.toHyphenDateString = function(needConnect=true) {
  var year = this.getFullYear();
  var month = this.getMonth() + 1;
  var date = this.getDate();
  if (month < 10) { month = "0" + month; }
  if (date < 10) { date = "0" + date; }
  var hours = this.getHours();
  var mins = this.getMin
  var mins = this.getMinutes();
  var second = this.getSeconds();
  if(!needConnect){
    return year+month+date;
  }else{
    return year + "-" + month + "-" + date + " " + hours + ":" + mins + ":" + second;
  }
};


//时间戳转为标准时间
function add0(m){return m<10? '0'+m : m }
export function format(shijianchuo,needConnect=true) {
  var time = new Date(shijianchuo);
  var y = time.getFullYear();
  var m = time.getMonth()+1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  // return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
  if(!needConnect){ //一般用于ajax请求
    return y+add0(m)+add0(d);
  }else{
    return y+'-'+add0(m)+'-'+add0(d);
  }
}

//运动函数
export function startMove(obj, json, fnEnd){
  clearInterval(obj.timer);
  obj.timer = setInterval(function(){
    var bStop = true; //假设所有的属性值运动到了目标值
    for(var attr in json){
      var start = 0;
      if(attr === 'opacity'){//透明度
        start = Math.round(parseFloat(getStyle(obj, attr))*100);
      }else{//非透明度属性
        start = parseInt(getStyle(obj, attr));
      }
      if(start != json[attr]){//若有属性值未运动到目标值，将bStop的值赋为false
        bStop = false;
      }
      var speed = (json[attr] - start)/6;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if(attr === 'opacity'){
        obj.style.filter = "alpha(opacity:'+ (start + speed) +')";
        obj.style.opacity = (start + speed)/100;
      }else{
        obj.style[attr] = start + speed + 'px';
      }
    }
    if(bStop){
      clearInterval(obj.timer);
      if(fnEnd)fnEnd();
    }
  }, 30);
}

//获取css属性
export function getStyle(obj, attr){//获取当前属性的值
  if(obj.currentStyle){
    return obj.currentStyle[attr];
  }else{
    return getComputedStyle(obj, false)[attr];
  }
}

// css属性设置
export function css(obj, attr, value) {
  switch (arguments.length) {
    case 2:
      if (typeof arguments[1] == "object") {    //批量设置属性
        for (var i in attr) obj.style[i] = attr[i]
      }
      else {    // 读取属性值
        return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
      }
      break;
    case 3:
      //设置属性
      obj.style[attr] = value;
      break;
    default:
      return "";
  }
}
// 是否拥有css名
export function hasClass(obj, cls) {
  return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
// 追加class类名
export function addClass(obj, cls) {
  if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}
// 移除class类名
export function removeClass(obj, cls) {
  if (hasClass(obj, cls)) {
    var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
    obj.className = obj.className.replace(reg, ' ');
  }
}

export function versionTip(){
  var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/)
  if (ver) {
    ver = parseInt(ver[1], 10)
    if(ver<9) {
      alert("当前系统版本过低，为影响用户体验，请先升级")
      return
    }
  }
}

// 修改知乎接口返回数据中的body中的图片链接
export function attachBodyContent(body) {
  return body.replace(/src="http\w{0,1}:\/\//g, 'src="https://images.weserv.nl/?url=');
}

//图片路径格式化
export function attachImageUrl(srcUrl) {
  if (srcUrl !== undefined) {
    return srcUrl.replace(/http\w{0,1}:\/\/p/g, 'https://images.weserv.nl/?url=p');
  }
}

//倒计时封装(doing)
export function countDown(countdown) {
  this.countdown = countdown
}
countDown.prototype.settime = function (obj) {
  if (countdown == 0) {
    obj.removeAttribute("disabled");
    // obj.value="免费获取验证码";（暂未定入参）
    countdown = 60;
    return;
  } else {
    obj.setAttribute("disabled", true); //自行修改disable样式
    // obj.value="重新发送(" + countdown + ")";（暂未定入参）
    countdown--;
  }
  setTimeout(function() {
        settime(obj) }
  ,1000)
}

//银行卡隔4位输入空格（doing）
export function fourSpacing() {
  $('#kahao').on('keyup', function(e) {
    //只对输入数字时进行处理
    if((e.which >= 48 && e.which <= 57) ||
        (e.which >= 96 && e.which <= 105 )){
      //获取当前光标的位置
      var caret = this.selectionStart
      //获取当前的value
      var value = this.value
      //从左边沿到坐标之间的空格数
      var sp =  (value.slice(0, caret).match(/\s/g) || []).length
      //去掉所有空格
      var nospace = value.replace(/\s/g, '')
      //重新插入空格
      var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim()
      //从左边沿到原坐标之间的空格数
      var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length
      //修正光标位置
      this.selectionEnd = this.selectionStart = caret + curSp - sp
    }
  })
}

//动态创建css引入 link href=""
export function createCssLink(cssURL) {
  let head = document.getElementsByTagName('head')[0]
  let linkTag = document.createElement('link')
  linkTag.id = 'dynamic-style'
  linkTag.href = cssURL
  linkTag.setAttribute('rel','stylesheet')
  linkTag.setAttribute('media','all')
  linkTag.setAttribute('type','text/css')
  head.appendChild(linkTag)
}
//删除css外链
export function delCssLink(id) {
  let cssLink =  document.getElementById(id)
  cssLink.parentNode.removeChild(cssLink)
}

let currentTitle = '招财猪商圈'
export function setTitle(title = '招财猪商圈') {
  if (!title) {
    return
  }
  document.title = title
  let ua = navigator.userAgent;
  if (/\bMicroMessenger\/([\d\.]+)/.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    var i = document.createElement('iframe');
    i.src = '//m.baidu.com/favicon.ico';
    i.style.display = 'none';
    i.onload = function () {
      setTimeout(function () {
        i.remove();
      }, 9);
    };
    document.body.appendChild(i);
  }
}

// 对饿了么图片路径进行修正
export function getImgPath(value) {
  let suffix
  if(!value){
    return 'http://test.fe.ptdev.cn/elm/elmlogo.jpeg'
  }
  if(value.indexOf('jpeg') !== -1){
    suffix = '.jpeg'
  }else {
    suffix = '.png'
  }
  let url = '/' + value.substr(0, 1) + '/' + value.substr(1, 2) + '/' + value.substr(3) + suffix;
  return imgBaseUrl + url
}











